/**
 * Copyright (c) 2011-2016, Eason Pan(pylxyhome@vip.qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;

import com.google.common.collect.Lists;
import com.jcbase.core.auth.common.CONST;
import com.jcbase.core.cache.CacheClearUtils;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.pojo.User;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.util.MyDigestUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.core.view.ZtreeView;
import com.jcbase.model.base.BaseSysGroup;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * @author eason 系统角色
 */
public class SysGroup extends BaseSysGroup<SysGroup> {

    /**
     * 
     */
    private static final long serialVersionUID = 2374713709626532804L;
    public static final SysGroup me = new SysGroup();

    /**
     * @author eason
     * @param uid
     * @return
     */
    public List<SysGroup> getSysGroupList(int uid) {

	return this.find("select * from sys_group where id in(select role_id from sys_user_role where user_id =?)",
		uid);
    }

    public List<SysGroup> getSysGroupIdList(int uid) {
	return this.find("select id from sys_group where id in(select role_id from sys_user_role where user_id =?)",
		uid);
    }

    public InvokeResult delete(String idStrs) {
	List<Integer> ids = CommonUtils.getIntegerListByStrs(idStrs);
	Set<Condition> conditions = new HashSet<Condition>();
	conditions.add(new Condition("id", Operators.IN, ids));
	this.delete(conditions);
	return InvokeResult.success();
    }

    public InvokeResult getZtreeViewList(HttpServletRequest request) {
	HashMap<String, List<Record>> groupTree = new HashMap<String, List<Record>>();

	SysUser user = IWebUtils.getCurrentSysUser(request);
	List<SysUserRole> list = SysRole.me.getRole(request);
	List<SysGroup> pageInfo;

	pageInfo = SysGroup.me.find("select * from sys_group where create_user_id = " + user.getId());

	// 根据组获取用户列表
	for (SysGroup sysGroup : pageInfo) {
	    StringBuilder sql = new StringBuilder();
	    sql.append(" select su.*,sug.group_id as groupId,sug.id as groupInfoId");
	    sql.append(" from sys_user su ");
	    sql.append(" left join  sys_user_group sug on sug.user_id = su.id ");
	    sql.append(" where su.create_user_id  = ");
	    sql.append(user.getId());
	    sql.append(" and group_id = ");
	    sql.append(sysGroup.getId());
	    List<Record> userList = Db.find(sql.toString());
	    if (sysGroup.getPId() == null) {
		groupTree.put(sysGroup.getName() + "|" + sysGroup.getId() + "|" + CONST.ROOT_SIZE, userList);
	    } else {
		groupTree.put(sysGroup.getName() + "|" + sysGroup.getId() + "|" + sysGroup.getPId(), userList);
	    }

	}

	List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
	ZtreeView zt = new ZtreeView(CONST.ROOT_SIZE, null, "分组列表", true);
	zt.setType("root");
	ServletContext ServletContext = request.getServletContext();
	String path = (String) ServletContext.getAttribute("res_url");
	zt.setIcon(path + "image/house.ico");
	ztreeViews.add(zt);
	for (String key : groupTree.keySet()) {

	    String groupName = key.split("\\|")[0];
	    String groupId = key.split("\\|")[1];
	    String groupPid = key.split("\\|")[2];
	    ZtreeView ztreeView = new ZtreeView();
	    ztreeView.setName(groupName);
	    ztreeView.setId(Integer.parseInt(groupId));
	    ztreeView.setpId(Integer.parseInt(groupPid));
	    ztreeView.setOpen(true);
	    ztreeView.setIcon(path + "image/folder.ico");
	    ztreeView.setType("group");
	    ztreeView.setObjId(groupId);

	    ztreeViews.add(ztreeView);
	    List<Record> userList = groupTree.get(key);
	    // 添加子节点
	    if (userList != null && !userList.isEmpty()) {
		for (Record sysUser : userList) {
		    // 如果被分组
		    ZtreeView childTree = new ZtreeView();
		    childTree.setpId(sysUser.getInt("groupId"));
		    childTree.setName(sysUser.getStr("name"));
		    childTree.setId(CONST.LEAF_SIZE);
		    childTree.setOpen(true);
		    childTree.setType("user");
		    childTree.setIcon(path + "image/user.ico");
		    childTree.setObjId(sysUser.getInt("groupInfoId").toString());
		    childTree.setUserId(sysUser.getInt("id"));
		    ztreeViews.add(childTree);
		}
	    }
	}

	// 添加所有未分组的
	// rootList = SysUser.me.find("select * from sys_user where
	// ISNULL(group_id) and create_user_id =" + user.getId());
	List<Record> rootList;
	StringBuilder sql = new StringBuilder();
	if (SysRole.me.checkIsAdmin(list)) {

	    sql.append("select su.*,sug.group_id,sug.id as groupInfoId");
	    sql.append(
		    " from sys_user su LEFT JOIN sys_user_group sug on (sug.user_id = su.id and sug.create_user_id =");
	    sql.append(user.getId() + ")");
	    sql.append("where ISNULL(sug.group_id)");
	} else {

	    sql.append("select su.*,sug.group_id,sug.id as groupInfoId");
	    sql.append(
		    " from sys_user su LEFT JOIN sys_user_group sug on (sug.user_id = su.id and sug.create_user_id =");
	    sql.append(user.getId() + ")");
	    sql.append("where ISNULL(sug.group_id)");
	    sql.append(" and su.create_user_id = 2084 ");
	}

	rootList = Db.find(sql.toString());

	if (rootList != null && !rootList.isEmpty()) {
	    for (Record sysUser : rootList) {
		ZtreeView childTree = new ZtreeView();
		childTree.setpId(CONST.ROOT_SIZE);
		childTree.setName(sysUser.getStr("name"));
		childTree.setId(CONST.LEAF_SIZE);
		childTree.setOpen(true);
		childTree.setType("user");
		childTree.setIcon(path + "image/user.ico");
		childTree.setObjId(String.valueOf(sysUser.get("groupInfoId")));
		childTree.setUserId(sysUser.getInt("id"));
		ztreeViews.add(childTree);
	    }
	}
	return InvokeResult.success(JsonKit.toJson(ztreeViews));
    }

    public InvokeResult getRoleZtreeViewList(Integer uid) {
	List<SysGroup> list = this.getSysGroups(uid);
	List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
	ztreeViews.add(new ZtreeView(10000, null, "角色列表", true));
	for (SysGroup role : list) {
	    ZtreeView ztreeView = new ZtreeView();
	    ztreeView.setId(role.getId());
	    ztreeView.setName(role.getName());
	    ztreeView.setOpen(true);
	    ztreeView.setpId(10000);
	    ztreeViews.add(ztreeView);
	}
	return InvokeResult.success(JsonKit.toJson(ztreeViews));
    }

    public List<SysRes> getSysMenus(Integer groupId) {
	SysGroup role = this.findById(groupId);
	if (role != null) {
	    List<SysRes> list = SysRes.me
		    .find("SELECT *,(CASE WHEN re.id IN (SELECT rr.res_id from sys_group_res rr WHERE rr.role_id="
			    + role + " ) THEN 1 ELSE 0 END) as selected FROM sys_res re where re.enabled=1");
	    return list;
	}
	return Lists.newArrayList();
    }

    public List<SysGroup> getSysGroups(Integer uid) {
	List<SysGroup> list = this
		.find("SELECT *,(CASE WHEN re.id IN (SELECT rr.role_id from sys_user_role rr WHERE rr.user_id=" + uid
			+ " ) THEN 1 ELSE 0 END) as selected FROM sys_group re where re.status=1");
	return list;
    }

    public InvokeResult saveMenuAssign(String menuIds, Integer roleId) {
	if (roleId.equals(1)) {
	    return InvokeResult.failure("超级管理员不能被修改");
	}
	if (CommonUtils.isNotEmpty(menuIds)) {// 改成批量插入
	    List<String> sqlList = Lists.newArrayList();
	    for (String id : menuIds.split(",")) {
		if (CommonUtils.isNotEmpty(id)) {
		    if (!Integer.valueOf(id).equals(10000))
			sqlList.add("insert into sys_group_res (role_id,res_id) values (" + roleId + ","
				+ Integer.valueOf(id) + ")");
		}
	    }
	    Db.batch(sqlList, 50);
	    CacheClearUtils.clearUserMenuCache();
	}
	return InvokeResult.success();
    }

    public InvokeResult addSave(Integer pid, String name, int userId) {

	new SysGroup().set("name", name).set("pId", pid).set("createdate", new Date()).set("create_user_id", userId)
		.save();
	return InvokeResult.success();
    }

    public InvokeResult updateSave(Integer gid, String name) {

	SysGroup group = this.findById(gid);
	group.set("name", name).update();
	return InvokeResult.success();
    }

    public List<SysGroup> getSysGroupNamelist() {
	return this.find("select id,name from sys_group where status = 1");
    }

    public String getRoleNames(String roleIds) {
	String sql = "select group_concat(name) as roleNames from sys_group where id in(" + roleIds + ")";
	SysGroup SysGroup = this.findFirst(sql);
	if (SysGroup != null) {
	    return SysGroup.getStr("roleNames");
	}
	return "";
    }

    public InvokeResult updateUserGroup(String userId, Integer groupId) {
	if (CommonUtils.isNotEmpty(userId)) {
	    for (String id : userId.split(",")) {
		if (CommonUtils.isNotEmpty(id)) {
		    Record user = Db.findById("sys_user", id).set("group_id", groupId);
		    Db.update("sys_user", user);
		}
	    }
	}
	return InvokeResult.success();
    }

    public InvokeResult deleteUserGroup(String userId) {
	if (CommonUtils.isNotEmpty(userId)) {
	    for (String id : userId.split(",")) {
		if (CommonUtils.isNotEmpty(id)) {
		    Record user = Db.findById("sys_user", id).set("group_id", null);
		    Db.update("sys_user", user);
		}
	    }
	}
	return InvokeResult.success();
    }

    /**
     * 插入用户和组
     */
    public InvokeResult insertUserGroup(List<User> list) {
	for (User user : list) {
	    List<SysUser> userList = SysUser.me.find("select * from sys_user where name = '" + user.getUser() + "'");
	    // 如果用户存在
	    if (!CollectionUtils.isEmpty(userList)) {
		// 删除用户用户以及角色
		SysUser sysUser = userList.get(0);
		List<SysUserRole> roleList = SysUserRole.me
			.find("select * from sys_user_role where user_id = " + sysUser.getId());
		if (!CollectionUtils.isEmpty(roleList)) {
		    for (SysUserRole role : roleList) {
			role.me.deleteById(role.getId());
		    }
		}
		sysUser.me.deleteById(sysUser.getId());
	    }
	    // 否则创建用户绑定组
	    SysUser sysUser = new SysUser();
	    sysUser.set("name", user.getUser()).set("params", user.getParams())
		    .set("pwd", MyDigestUtils.shaDigestForPasswrod("123456")).set("createdate", new Date())
		    .set("des", user.getCommon());
	    if (user.getGroup() != null) {
		List<SysGroup> groupList = SysGroup.me
			.find("select * from sys_group where name ='" + user.getGroup() + "'");
		// 如果组名存在，则不创建直接插入
		if (groupList != null && groupList.size() > 0) {
		    SysGroup group = groupList.get(0);
		    sysUser.set("group_id", group.getId()).save();
		} else {
		    // 如果组名不存在，则创建插入
		    SysGroup group = new SysGroup();
		    group.set("name", user.getGroup()).set("createdate", new Date()).save();
		    sysUser.set("group_id", group.getId()).save();
		}
	    } else {
		sysUser.save();
	    }

	}
	return InvokeResult.success();
    }

}
